/***WXManager By GYLite 2022-12-26
 * 微信sdk管理器，提供微信小游戏对接平台接口
*/
class WXManager {	
	private static _instance: WXManager;
	public static game: Main;
	public static getInstance(): WXManager {
		if (WXManager._instance == null) 
		{
			WXManager._instance = new WXManager;
			if(!egret.wxgame.wx)
			{
				//非微信环境，注入空函数防止报错
				for(var key in  WXManager._instance)
				{
					WXManager._instance[key] = function():any{return {}};
				}
			}
		}		
		return WXManager._instance;
	}
	
	public version: string = "v1.0.0";
	public gameScale: number = 1;
	/**炫耀*/public static SHARETYPE_SHOWUP = 1;

	public static bitmap: egret.Bitmap;
	public rewardVideoAd: any;
	public bannerAd: any;
	public wxData: any;

	public shareTicket = "";
	public userInfo: any;
	private _wxCode: string;
	private _appid:string = "wx81756281893c1f8e";
	private _appSecret:string = "f8d8981f7a697b3e24369db16187cebe";
	public openid:string;
	public btn: any;//授权按钮	
	public authorUI:IUIBase;		
	private _userInfoCallBack:Function;
	private _userInfoCallObj:any;
	public constructor() {
		var s = this;

	}
	/**显示广告视频
	 * @param onfufilled 观看完毕回调
	 * @param onrejected 观看失败回调
	 * @param adUnitId 广告id
	*/
	public showRewardVideo(onfulfilled?: (value: Object) => Object | PromiseLike<Object>, onrejected?: (reason: any) => Object | PromiseLike<Object>,adUnitId:string = 'www.tanchishe.com') {
		var s = this;
		if (s.rewardVideoAd == null) {
			s.rewardVideoAd = egret.wxgame.wx.createRewardedVideoAd({ adUnitId: adUnitId });
		}
		s.rewardVideoAd.show().then(onfulfilled, onrejected);
		s.bannerAd = egret.wxgame.wx.createBannerAd({ adUnitId: adUnitId,style:{left:10,top:1200,width:620,height:200}});
	}
	/**显示广告栏	 
	 * @param adUnitId 广告id
	*/
	public showBannerAd(adUnitId:string='www.tanchishe.com'): void {
		var s = this;
		if (s.bannerAd == null) {
			s.bannerAd = egret.wxgame.wx.createBannerAd({ adUnitId: adUnitId, style: { left: 10, top: 1200, width: 620, height: 200 } });
		}
		s.bannerAd.show();
	}
	/**监听右上角分享事件*/
	public onShowShare(callBack:Function,thisObject:any):any
	{
		egret.wxgame.wx.onShareAppMessage(callBack.bind(thisObject));		
	}
	/**分享*/
	public showShare(title:string=null,img:any=null,callBack:Function=null,thisObject:any=null) {
		if(title == null)
			title = "";
		if(img == null)
			img = "https://miaoqujianzhi.xunguanggame.com/img/share.png";		
		var func:Function = egret.wxgame.wx.shareAppMessage;
		func({
				title:title, 
				imageUrl:img, 
				success:(callBack?callBack.bind(thisObject):null),
				fail:(callBack?callBack.bind(thisObject):null)
			});
	}
	/**发送数据到开放域*/
	public sendOpenData(obj: any): void {
		let openDataContext = egret.wxgame.wx.getOpenDataContext();
		openDataContext.postMessage(obj);
	}
	/**获取开放域画布*/
	public getSharedCanvasBitmap(w:number,h:number): egret.Bitmap {
		if (WXManager.bitmap == null) {
			//主要示例代码开始
			const bitmapdata = new egret.BitmapData(window["sharedCanvas"]);
			bitmapdata.width = w;
			bitmapdata.height = h;
			bitmapdata.$deleteSource = false;
			const texture = new egret.Texture();
			texture.bitmapData = bitmapdata;
			WXManager.bitmap = new egret.Bitmap(texture);
		}

		return WXManager.bitmap;
	}
	/**保存local数据*/
	public saveLocalStorage(): void {
		var s = this;
		egret.wxgame.wx.setStorageSync("cutPaper_GYLite_2048", s.wxData);
	}
	/**读取local数据*/
	public readLocalStorage(): any {
		var s = this;
		s.wxData = egret.wxgame.wx.getStorageSync("cutPaper_GYLite_2048");
		if (s.wxData == "" || s.wxData == null) {
			var dt: Date = new Date;
			s.wxData = { date: dt.getDate() };//自定义数据结构，时间是必须的，用于校验刷新
		}
		console.log("缓存数据：", s.wxData);
		return s.wxData;
	}
	/**检查loaclStorage的数据是否过期*/
	public checkDateUpdate(): boolean {
		var s = this;
		var dt: Date = new Date;
		if (dt.getDate() != s.wxData.date) {
			s.wxData.date = dt.getDate();
			s.wxData.boxNum = 100;
			s.wxData.snakeHpAdd = 0;
			s.saveLocalStorage();
			return true;
		}
		return false;
	}

	/** 用户托管数据 如排行榜数据*/
	public saveUserCloudStorage(value:number) {
		var kvDataList = [{key: "score", value:value}];
		let object = { KVDataList: kvDataList,success:null,fail:null,complete:null };
		egret.wxgame.wx.setUserCloudStorage(object);
	}

	

	public vibrateShort(suc: (res: any) => void, fal: (res: any) => void, comp: (res: any) => void): void {
		egret.wxgame.wx.vibrateShort({ success: suc, fail: fal, complete: comp });
	}

	public openMiniGame() {
		egret.wxgame.wx.navigateToMiniProgram({
			appId: window["flow"].appid,
			path: window["flow"].path
		})
	}
	public get wxCode(): string {
		return this._wxCode;
	}
	public setWXCode(data): void {
		let s = this;
		s._wxCode = data.code;
	}
	private setUserInfo(data): void {
		let s = this;
		s.userInfo = data.userInfo;		
		if(s._userInfoCallBack!=null)
		{
			s._userInfoCallBack.call(s._userInfoCallObj);
			s._userInfoCallBack = s._userInfoCallObj = null;
		}
	}
	/**微信登陆*/
	public login(authorUI:IUIBase=null,userInfoCallBack:Function=null,thisObj:any=null): void {
		let s = this;		
		s.authorUI = authorUI;
		s._userInfoCallBack = userInfoCallBack;
		s._userInfoCallObj = thisObj;
		egret.wxgame.wx.login({
			success: s.loginSuccess.bind(s),
			fail: s.loginFail.bind(s),
			complete: null
		})
	}
	private loginSuccess(data: any): void {
		let s = this;
		s.setWXCode(data);
		egret.wxgame.wx.request({
		url: `https://api.weixin.qq.com/sns/jscode2session?appid=${s._appid}&secret=${s._appSecret}&js_code=${s._wxCode}&grant_type=authorization_code`,
			success:(res)=>{				
				WXManager.getInstance().openid=res.data.openid				
				s.getUserInfo();
			}
		});		
	}
	private loginFail(data: any): void {
		console.error("微信登录失败！");
	}

	/**获取用户信息，成功后调用setUseInfo设置用户信息*/
	public getUserInfo(): void {
		let s = this;
		egret.wxgame.wx.getUserInfo({
			openIdList: null,
			lang: "zh-cn",
			success: s.getUserInfoSucess.bind(s),
			fail: s.getUserInfoFail.bind(s),
			complete: null,
		})
	}	

	private getUserInfoSucess(data: any): void {
		let s = this;		
		s.setUserInfo(data);
	}
	/**获取用户信息失败，将重新调用授权窗口，在外部窗口调WXManager里的showAuthorBtn显示授权按钮，准确盖在外部UI的指定位置上*/
	private getUserInfoFail(): void {
		let s= this;
		if(s.authorUI)
			s.authorUI.show(null);
		else
			s.showAuthorBtn(GYLite.GYSprite.stage.stageWidth - 400 >> 1,GYLite.GYSprite.stage.stageHeight - 162 >> 1,400,162,"请授权微信用户信息")
	}
	/**获取启动参数*/
	public getLaunchOptionsSync():any
	{
		return egret.wxgame.wx.getLaunchOptionsSync();
	}
	/**显示当前微信分享按钮*/
	public showShareMenu(obj:any):void
	{
		egret.wxgame.wx.showShareMenu(obj);
	}
	/**更新微信分享设置*/
	public updateShareMenu(obj:any):void
	{
		egret.wxgame.wx.updateShareMenu(obj);
	}
	/**监听切到后台事件*/
	public onHide(callBack:Function,thisObject:any):void
	{
		egret.wxgame.wx.onHide(callBack.bind(thisObject));
	}
	/**跳转其他小程序*/
	public navigateToMiniProgram(obj:any):void
	{
		egret.wxgame.wx.navigateToMiniProgram(obj);
	}
	/**取消监听切到后台事件*/
	public offHide(callBack:Function,thisObject:any):void
	{
		egret.wxgame.wx.offHide(callBack.bind(thisObject));
	}
	/**监听切到前台事件*/
	public onShow(callBack:Function,thisObject:any):void
	{
		egret.wxgame.wx.onShow(callBack.bind(thisObject));
	}
	/**取消监听切到前台事件*/
	public offShow(callBack:Function,thisObject:any):void
	{
		egret.wxgame.wx.offShow(callBack.bind(thisObject));
	}
	/**显示模态窗口
	 * @param title 标题
	 * @param content 内容
	 * @param callBack 回调，参数res，res.comfirm为true则按的确认，res.cancel为true则按的取消
	 * @param thisObject 回调域
	*/
	public showModal(title:string,content:string,callBack:Function=null,thisObject:any = null):void
	{
		egret.wxgame.wx.showModal({
			title:title,
			content:content,
			showCancel:true,
			cancelText:"取消",
			cancelColor:"#000000",
			confirmText:"确定",			
			confirmColor:"#575c80",
			success:callBack.bind(thisObject),
			fail:null,
			complete:null
		});
	}
	/**显示授权按钮，设置尺寸准确盖住UI上面
	 * @param x 坐标x
	 * @param y 坐标y
	 * @param w 按钮宽度
	 * @param h 按钮高度
	*/
	public showAuthorBtn(tx: number, ty: number, w:number = 400, h:number=162, msg:string=""): void {let s= this;
		if (s.btn == null) {
			s.btn = egret.wxgame.wx.createUserInfoButton({
				withCredentials: true,
				type: 'text',
				text: msg,
				style:
				{
					left: tx,
					top: ty,
					width: w,
					height: h,
					lineHeight: 40,
					backgroundColor: '#00ffff00',
					color: '#ffffff',
					textAlign: 'center',
					fontSize: 16,
					borderRadius: 4
				}
			});
		}

		s.btn.show();
		s.btn.onTap(function (data) {
			let wxMgr:WXManager = WXManager.getInstance();
			wxMgr.setUserInfo(data);
			wxMgr.btn.hide();
			wxMgr.authorUI.hide();			
		});
	}
	/**对接口进行授权调用，需要授权调用的接口参考WXManager常量*/
	private authorizeCall(obj:any,scopeKey:string):void
	{
		egret.wxgame.wx.getSetting({
			success:function(res:any):void {
				console.log(res.authSetting);
				if(res.authSetting[scopeKey])
				{//已经授权过
					obj.func(obj.param);
				}
				else
				{//未授权，进行授权
					egret.wxgame.wx.authorize({
						scope:scopeKey,
						success:function(res:any):void {
							obj.func(obj.param);
						},
						fail:function(res:any):void {
							obj.param.fail(null);
						},
						complete:function(res:any):void {},
					})
				}
			},
			fail:function(res:any):void {
						
			},
			complete:function(res:any):void {
						
			}
		});
	}
	
	private saveToAlbum(filePath:string,callBack:Function=null,thisObject:any=null):void
	{let s = this;
		s.authorizeCall({
			func:egret.wxgame.wx.saveImageToPhotosAlbum,
			param:{
					filePath: filePath,
					success:callBack?callBack.bind(thisObject):null,
					fail:callBack?callBack.bind(thisObject):null,
					complete:function(res: any){
						console.log("saveImageToPhotosAlbum-完成");
					}
		}},WXManager.SCOPE_ALBUM);
	}
	private _cutCallBack:Function;	
	private _cutObject:any;
	private _cutOperType:string;
	private _cutMsg:string;
	/**微信截图
	 * @param tex 纹理
	 * @param callBack 完成回调 返回res对象，分别对应0 截图 1分享 2保存到相册的数据返回内容，详情看微信api
	 * @param thisObject 回调域
	 * @param operType 截图后的操作类型 参考WXManager常量
	 * @param x 截图x坐标
	 * @param y 截图y坐标
	 * @param w 截图宽度
	 * @param h 截图高度
	 * 
	*/
	public async shortcut(tex:egret.Texture=null,callBack:Function=null,thisObject:any=null,operType:string=null,x:number=0,y:number=0,w:number=500,h:number=400,dsWidth:number=500,dsHeight:number=400,shareMsg:string="请来挑战，只求一败！") {		
		//await WXManager.getInstance().canvasToTempFilePath(0,0,this.width,this.height);
		let s= this;
		s._cutOperType = operType;
		s._cutCallBack = callBack;
		s._cutObject = thisObject;		
		s._cutMsg = shareMsg;
		let cvs:any;
		cvs = egret.web.convertImageToCanvas(tex);		
		await cvs.toTempFilePath({
			x: x,
			y: y,
			width: w,
			height: h,
			destWidth: dsWidth,
			destHeight: dsHeight,
			fileType: "jpg",
			quality: 1,
			success: s.toTempFilePathSuccess.bind(s),
			fail: s.toTempFilePathfail.bind(s),
			complete: (res: any) => { 
				console.log("toTempFilePathcomplete", res); 				
			}
		})
	}

	private toTempFilePathSuccess(res:any): void {
		// console.log("toTempFilePathfail", res,res.tempFilePath);
		let s = this;
		if(s._cutOperType == WXManager.SHORTCUT_SHARE)
		{
			s.showShare(s._cutMsg, res.tempFilePath, s._cutCallBack, s._cutObject);//炫耀分享
			setTimeout(s._cutCallBack.bind(s._cutObject),1000);
		}			
		else if(s._cutOperType == WXManager.SHORTCUT_ALBUM)
			s.saveToAlbum(res.tempFilePath, s._cutCallBack, s._cutObject);
		else
			s._cutCallBack.call(s._cutObject, res);
	}

	private toTempFilePathfail(res:any): void {
		// console.log("toTempFilePathfail", res);
		let s = this;
		if(s._cutCallBack!=null)
			s._cutCallBack.call(s._cutObject, res);
	}

	public static SCOPE_WERUN:string = "scope.werun";
	public static SCOPE_USERINFO:string = "scope.userInfo";
	public static SCOPE_USERLOCATION:string = "scope.userLocation";
	public static SCOPE_ALBUM:string = "scope.writePhotosAlbum";

	/**保存到相册*/public static SHORTCUT_ALBUM:string = "cut_album";
	/**分享截图*/public static SHORTCUT_SHARE:string = "cut_share";
}